package com.yiren.dbaa.module.practice_set.site.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yiren.dbaa.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LWB
 * on 2022/10/12
 * Describe 用户选择的适配器
 */
public class SelectUserAdapter extends BaseAdapter {

    private Context context;
    private List<String> list;
    private List<Boolean> isChecks = new ArrayList<>();
    private int checkPosition = 0;  //默认选中第一个

    public SelectUserAdapter(Context context, List<String> list,int defIdIndez) {
        this.context = context;
        this.list = list;
        isChecks.clear();
        for (int i = 0; i < list.size(); i++) {
            if (i == defIdIndez) {
                checkPosition = i;
                isChecks.add(true);
            } else {
                isChecks.add(false);
            }
        }
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder mHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_select_name, parent, false);
            mHolder = new ViewHolder(convertView);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        mHolder.tvUser.setText(list.get(position));
        mHolder.cbUserChoose.setChecked(isChecks.get(position));
        mHolder.llUserChoose.setOnClickListener(v -> {
            if (position != checkPosition) {
                isChecks.set(checkPosition, false);
                isChecks.set(position, true);
                checkPosition = position;
                notifyDataSetChanged();
            }
        });
        return convertView;
    }

    class ViewHolder {
        LinearLayout llUserChoose;
        TextView tvUser;
        CheckBox cbUserChoose;

        public ViewHolder(View itemView) {
            llUserChoose = (LinearLayout) itemView.findViewById(R.id.ll_user_choose);
            tvUser = (TextView) itemView.findViewById(R.id.tv_user);
            cbUserChoose = (CheckBox) itemView.findViewById(R.id.cb_user_choose);
        }
    }

    public int getCheckPosition() {
        return checkPosition;
    }

}
